<script setup lang="ts">
import { onActivated, onDeactivated, onMounted, onUnmounted, onUpdated, ref } from 'vue'
import { LoadZh_Cn } from './ts/lang'
import tinymce from 'tinymce'
import 'tinymce/models/dom'
import 'tinymce/skins/ui/oxide/skin.min.css'
import 'tinymce/skins/ui/oxide/content.min.css'
import 'tinymce/skins/content/default/content.css'
import 'tinymce/themes/silver' // 引入 TinyMCE 主题文件
import 'tinymce/icons/default' // 引入 TinyMCE 默认的图标集
import 'tinymce/plugins/link' // 引入 TinyMCE 需要使用的插件，比如链接插件
import 'tinymce/plugins/image'
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/code'
import 'tinymce/plugins/link'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/template'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/image'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/importcss'
import { Editor } from 'tinymce/tinymce'
LoadZh_Cn(tinymce)
const editerRef = ref<HTMLElement>()
let edit: Editor | null = null
let content = ''
onMounted(() => {
  tinymce
    .init({
      target: editerRef.value,
      skin: false,
      width: '100%',
      // menubar:false,
      content_css: false,
      language: 'zh_CN',
      toolbar_sticky: false,
      promotion: false,
      branding: false
    })
    .then((arr) => {
      edit = arr[0]
      edit.setContent(content)
    })
})
function save() {
  return edit?.getContent()
}

onDeactivated(() => {
  content = edit?.getContent() || ''
  edit?.remove()
})
onActivated(async () => {
  let arr = await tinymce.init({
    target: editerRef.value,
    skin: false,
    width: '100%',
    // menubar:false,
    content_css: false,
    language: 'zh_CN',
    toolbar_sticky: false,
    promotion: false,
    branding: false
  })
  edit = arr[0]
  edit?.setContent(content)
})
async function setContent(data: string) {
  edit?.setContent(data)
  content = data
}
defineExpose({
  save,
  setContent
})
</script>
<template>
  <div class="editer" ref="editerRef"></div>
</template>
<style scoped lang="less">
.editer {
  height: 500px;
}
</style>
